import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export type ThemeMode = 'light' | 'dark' | 'auto'

export interface Notification {
  id: number
  title: string
  content: string
  time: string
  avatar: string
  color: string
  read: boolean
}

export const useAppStore = defineStore('app', () => {
  // 状态
  const sidebarCollapsed = ref(false)
  const themeMode = ref<ThemeMode>('auto')
  const notificationsCount = ref(0)
  const isLoading = ref(false)
  const appVersion = ref('1.0.0')

  // 通知数据
  const notifications = ref<Notification[]>([
    {
      id: 1,
      title: '系统通知',
      content: '欢迎使用皮影快闪创作平台，点击查看新手教程。',
      time: '刚刚',
      avatar: '',
      color: '#2080f0',
      read: false
    },
    {
      id: 2,
      title: '项目提醒',
      content: '您的项目"皮影动画示例"已成功保存。',
      time: '10分钟前',
      avatar: '',
      color: '#18a058',
      read: false
    }
  ])
  
  // 计算属性
  const hasNotifications = computed(() => notifications.value.filter(n => !n.read).length > 0)
  const unreadNotificationsCount = computed(() => notifications.value.filter(n => !n.read).length)
  const isDarkTheme = computed(() => {
    if (themeMode.value === 'auto') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    return themeMode.value === 'dark'
  })
  
  // 动作
  function toggleSidebar() {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  function setThemeMode(mode: ThemeMode) {
    themeMode.value = mode
    localStorage.setItem('themeMode', mode)
  }
  
  function toggleTheme() {
    const newMode = themeMode.value === 'dark' ? 'light' : 'dark'
    setThemeMode(newMode)
  }
  
  function loadSettings() {
    const savedTheme = localStorage.getItem('themeMode') as ThemeMode
    if (savedTheme) {
      themeMode.value = savedTheme
    }
  }
  
  function setLoading(status: boolean) {
    isLoading.value = status
  }

  function markNotificationAsRead(id: number) {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }

  function clearNotifications() {
    notifications.value = []
  }

  function addNotification(notification: Omit<Notification, 'id'>) {
    const newId = Math.max(0, ...notifications.value.map(n => n.id)) + 1
    notifications.value.unshift({
      ...notification,
      id: newId
    })
  }

  // 初始化
  loadSettings()

  return {
    sidebarCollapsed,
    themeMode,
    notificationsCount,
    notifications,
    isLoading,
    appVersion,
    hasNotifications,
    unreadNotificationsCount,
    isDarkTheme,
    toggleSidebar,
    setThemeMode,
    toggleTheme,
    loadSettings,
    setLoading,
    markNotificationAsRead,
    clearNotifications,
    addNotification
  }
})